<template>
  <div class="assistant-container">
    <h2 class="assistant-title">Deepseek智能分析助手</h2>
    <div class="chat-box">
      <div v-for="(msg, idx) in messages" :key="idx" :class="['msg', msg.role]">
        <!-- 序号 -->
        <div class="msg-index">{{ idx + 1 }}</div>
        <div class="avatar">
          <span v-if="msg.role==='user'">🧑‍💻</span>
          <span v-else>🤖</span>
        </div>
        <div class="bubble" v-if="msg.role === 'assistant'" v-html="renderMarkdown(msg.content)"></div>
        <div class="bubble" v-else>{{ msg.content }}</div>
      </div>
    </div>
    <div class="input-area">
      <el-input
        v-model="input"
        placeholder="请输入你的问题"
        @keyup.enter="send"
        :disabled="loading"
        clearable
        size="large"
      />
      <el-button type="primary" @click="send" :loading="loading" size="large">发送</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { marked } from 'marked' // 新增

const input = ref('')
const loading = ref(false)
const messages = ref([
  { role: 'assistant', content: '你好，我是你的智能分析助手，有什么可以帮你？' }
])

const chatBoxRef = ref(null)

async function send() {
  if (!input.value.trim()) return
  const question = input.value
  messages.value.push({ role: 'user', content: question })
  input.value = ''
  loading.value = true
  await nextTick()
  scrollToBottom()
  try {
    // DeepSeek AI 接入
    const payload = JSON.stringify({
      model: 'deepseek-chat',
      messages: [
        { role: 'system', content: '你是一个有用的智能分析助手。' },
        ...messages.value.map(m => ({ role: m.role, content: m.content }))
      ]
    })

    const res = await axios.post(
      '/api/deepseek',
      payload,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )
    const answer = res.data.choices?.[0]?.message?.content || 'AI没有返回内容'
    messages.value.push({ role: 'assistant', content: answer })
  } catch (e) {
    ElMessage.error('AI服务请求失败')
    messages.value.push({ role: 'assistant', content: '抱歉，AI服务暂时不可用。' })
  }
  loading.value = false
  await nextTick()
  scrollToBottom()
}

function scrollToBottom() {
  const box = document.querySelector('.chat-box')
  if (box) box.scrollTop = box.scrollHeight
}

watch(messages, (val) => {
  localStorage.setItem('assistantMessages', JSON.stringify(val))
}, { deep: true })

onMounted(() => {
  const saved = localStorage.getItem('assistantMessages')
  if (saved) messages.value = JSON.parse(saved)
})

// 新增：把markdown转为html
function renderMarkdown(md) {
  return marked.parse(md || '')
}
</script>

<style scoped>
.assistant-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  background: none;
  position: relative;
}

.assistant-title {
  font-size: 24px;
  font-weight: 700;
  margin: 30px 0 18px 0;
  color: #222;
  letter-spacing: 1px;
}

.chat-box {
  width: 100%;
  max-width: 1200px;
  flex: 1;
  min-height: 300px;
  margin-bottom: 80px; /* 留出输入框空间 */
  background: none;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 15px;
}

.msg {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
}

.msg.user {
  flex-direction: row-reverse;
  justify-content: flex-end;
}

.msg.assistant {
  flex-direction: row;
  justify-content: flex-start;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin: 0 12px;
  background: #eaf6ff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
}

.bubble {
  display: inline-block;
  padding: 12px 18px;
  border-radius: 16px;
  background: #f1f3f4;
  color: #333;
  max-width: 80%;
  word-break: break-all;
  font-size: 16px;
  line-height: 1.7;
}

.msg.user .bubble {
  background: #d0ebff;
  color: #409eff;
  margin-left: auto; /* 让用户气泡靠右 */
}

.msg.assistant .bubble {
  margin-right: auto; /* 让助手气泡靠左 */
}

.input-area {
  width: 100%;
  max-width: 1100px;
  display: flex;
  gap: 10px;
  align-items: center;
  margin: 0 0 24px 0;
  justify-content: flex-start;
  position: absolute;
  left: 0;
  bottom: 0;
  background: inherit;
  padding-left: 0;
}

.bubble-loading {
  margin-right: 8px;
  vertical-align: middle;
}

.msg-index {
  width: 32px;
  min-width: 32px;
  text-align: center;
  color: #bbb;
  font-size: 14px;
  margin-top: 8px;
}

.bubble ul,
.bubble ol {
  margin: 0 0 0 0;         /* 可选，去掉多余外边距 */
  padding-left: 1.5em; 
  list-style-position: inside;    /* 关键：给左侧留出序号/点的空间 */
}

.bubble li {
  margin: 0;
  padding: 0;
}

</style>